// Skapar en enkelt login-ruta
// Kan med fördel extendas och anpassas grafiskt.

package com.sundhage.misc {
	import com.sundhage.gui.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.text.*;

	public class JSLoginWindow extends Sprite {
		static public const TRY:String = "checkpass";
		
		protected var txtName:JSRichText;
		protected var txtPass:JSRichText;
		protected var pad:int = 5;
		protected var round:int = 5;
		protected var okBtn:Sprite;
		protected var hasName:Boolean;
		
		public var pass:String = "";
		public var namn:String = "";
		protected var font:*;
		
		public function wrongPassword():void {
			if (hasName) {
				stage.focus = txtName.getTextfield();
				txtName.getTextfield().text = "";
			} else {
				stage.focus = txtPass.getTextfield();
			}		
			txtPass.getTextfield().text = "";
			okBtn.buttonMode = true;
			okBtn.alpha = 1;
			okBtn.addEventListener(MouseEvent.CLICK, onClick);			
		}
		
		protected function getInputField(w:int, h:int):JSRichText {
			var settings:JSRichTextSettings = new JSRichTextSettings({
				 text:"",
				 generalPad:0,
				 type:TextFieldType.INPUT,
				 txtEmbed:true,
				 txtFormat:JSText.CreateTextFormat(12, font),
				 height:h,
				 width:w,
				 txtMultiline:false,
				 hasScroller:false
			
			});
			var assets:JSRichTextAssets = new JSRichTextAssets({
				background:new BitmapData(10,10,true,0x55ffffff)
			});
			
			var field:JSRichText = new JSRichText(settings, assets);
			return field;
		}
		
		protected function onClick(e:Event):void {
			pass = txtPass.getText();
			if (hasName)
				namn = txtName.getText();
			okBtn.removeEventListener(MouseEvent.CLICK, onClick);
			okBtn.buttonMode = false;
			okBtn.alpha = 0.5;
			dispatchEvent(new Event(TRY));
		}
		
		protected function init(w:int, h:int, font:*, okBtn:Sprite):void {
			this.font = font;
			graphics.beginFill(0x0, 0.2);
			graphics.drawRoundRect(0,0,w,h,round,round);
			graphics.endFill();
			var yadd:int = pad;
			if (hasName) {
				txtName = getInputField(w-pad*2,20);
				txtName.getTextfield().multiline = false;
				txtName.x = pad;
				txtName.y = pad;
				addChild(txtName);
				yadd = txtName.y+txtName.height;
			}
			
			txtPass = getInputField(w-pad*2,20);
			txtPass.getTextfield().displayAsPassword = true;
			txtPass.getTextfield().multiline = false;
			txtPass.x = pad;
			txtPass.y =yadd+pad;
			addChild(txtPass);
			this.okBtn = okBtn;
			okBtn.x = w-okBtn.width-pad;
			okBtn.y = h-okBtn.height-pad;
			okBtn.buttonMode = true;
			okBtn.addEventListener(MouseEvent.CLICK, onClick);
			addChild(okBtn);
		}
		protected function onStage(e:Event):void {
			if (hasName)
				stage.focus = txtName.getTextfield();
			else
				stage.focus = txtPass.getTextfield();
		}
		public function JSLoginWindow(w:int, h:int, font:*, okBtn:Sprite, hasName:Boolean = true) {			
			this.hasName = hasName;
			init(w,h, font, okBtn);
			addEventListener(Event.ADDED_TO_STAGE, onStage);
		}
		
	}
}